import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';
import { t } from '@lingui/macro';
import moment from 'moment';

export default class RoadStationStore {
  _args = {
    search: {},
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  data = [];
  shiftInfo = {};
  loading = false;
  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  get api() {
    return api;
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    const { keyword } = search;
    if (keyword) {
      const orderInfo = yield api.orderSearch({ search: { orderIds: [keyword] } });
      const { orderType, busOrder, scOrder } = orderInfo[0] || {};
      search.departureDate = moment().add('1', 'day').format('YYYY-MM-DD');
      if (orderType && orderType == 2) {
        const { startMinorArea, endMinorArea } = scOrder;
        search.onStationId = startMinorArea;
        search.offStationId = endMinorArea;
      } else if (orderType && orderType == 3) {
        const { from, to } = busOrder;
        const { station: onStationId } = from;
        const { station: offStationId } = to;
        search.onStationId = onStationId;
        search.offStationId = offStationId;
      }
    }
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      this.data = yield api.search({ search, pg });
    } catch (error) {
      console.error(error);
      this.total = 0;
      this.data = [];
    } finally {
      this.loading = false;
    }
  }

  * get(id) {
    const res = yield api.get(id);
    return observable(res);
  }

  * _reload() {
    yield this.query();
  }

  * update(price) {
    yield api.update({ ...price });
    yield this._reload(price);
  }

  * create(price) {
    yield api.create({ ...price });
    yield this._reload(price);
  }

  * remove(price) {
    yield api.remove(price.id);
    yield this._reload(price);
  }

  * getRoute(id) {
    return yield api.getRoute(id);
  }

  * getShift(id) {
    return yield api.getShift(id);
  }

  idx(size, page, i) {
    return page * size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
    // _.mergeWith(this._args.pg, pg, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }
}
